<!--孔位管理模块-->
<template>
  <div class="container">
    <div class="app-container">
      <!-- 工具栏 -->
      <div class="filter-container">
        <el-button size="mini" type="primary" @click="showDialog = true">添加孔位</el-button>
        <el-input v-model="queryParams.holeLocationId" placeholder="孔号" style="width: 200px; margin-left: 10px;" size="mini" clearable/>
        <el-input v-model="queryParams.pumpNumber" placeholder="抽/注水层位" style="width: 200px; margin-left: 10px;" size="mini" clearable/>
        <el-button type="primary" size="mini" style="margin-left: 10px;" @click="handleSearch">查询</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="markers">
        <!-- 孔号列 -->
        <el-table-column prop="hole_id" align="center" width="200" label="孔号">
          <template v-slot="{ row }">
            <span>{{ row.holeLocationId }}</span>
          </template>
        </el-table-column>

        <!-- 孔位类型列 -->
        <el-table-column prop="type" align="center" label="孔位类型">
          <template v-slot="{ row }">
            <span>{{ getTypeName(row.type) }}</span>
          </template>
        </el-table-column>

        <!-- 抽/注水层位列 -->
        <el-table-column prop="pumpNumber" align="center" label="抽/注水层位">
          <template v-slot="{ row }">
            <span>{{ row.pumpNumber }}</span>
          </template>
        </el-table-column>

        <!-- 修改后的含水层观测水位列 -->
        <el-table-column prop="water_level" align="center" label="含水层观测水位">
          <template v-slot="{ row }">
            <span v-if="row.waterLevel || row.waterLevel === 0">{{ row.waterLevel }}m</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="btnEditOK(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button
type="text"
size="mini"
@click="btnPermission(
                row.holeLocationId,
                row.pageX,
                row.pageY,
                row.pageZ,
                row.type,
                row.waterLevel,
                row.pumpNumber,
                row.permeabilityCoefficient,
                row.yieldPerUnit,
                row.pumpDepthDown,
                row.pumpDepthUp
          )">查看详情</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
<!--              <el-popconfirm title="确定删除吗？" @onConfirm="confirmDel(row.id)">-->
<!--                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>-->
<!--              </el-popconfirm>-->
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <!--      <el-row type="flex" style="height:60px" align="middle" justify="end">-->
      <!--        &lt;!&ndash; 放置分页组件 &ndash;&gt;-->
      <!--        <el-pagination-->
      <!--          :page-size="pageParams.pagesize"-->
      <!--          :current-page="pageParams.page"-->
      <!--          :total="pageParams.total"-->
      <!--          layout="prev, pager, next"-->
      <!--          @current-change="changePage"-->
      <!--        />-->
      <!--      </el-row>-->
    </div>
    <!-- 修改后的新增孔位弹层 -->
    <el-dialog width="500px" title="新增孔位" :visible.sync="showDialog" @close="btnCancel">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <!-- 坐标输入 -->
        <el-form-item label="孔号" prop="holeLocationId">
          <el-input v-model.number="roleForm.holeLocationId" type="text" style="width:300px" size="mini"/>
        </el-form-item>
        <el-form-item label="X坐标" prop="x">
          <el-input v-model.number="roleForm.x" type="number" style="width:300px" size="mini"/>
        </el-form-item>
        <el-form-item label="Y坐标" prop="y">
          <el-input v-model.number="roleForm.y" type="number" style="width:300px" size="mini"/>
        </el-form-item>
        <el-form-item label="Z高度" prop="z">
          <el-input v-model.number="roleForm.z" type="number" style="width:300px" size="mini"/>
        </el-form-item>

        <!-- 孔位类型选择 -->
        <el-form-item label="孔位类型" prop="type">
          <el-select
            v-model="roleForm.type"
            placeholder="请选择类型"
            @change="handleTypeChange"
            style="width:300px"
          >
            <el-option label="地质钻孔" :value="1"/>
            <el-option label="水文长观孔" :value="2"/>
            <el-option label="抽水钻孔" :value="3"/>
            <el-option label="混合孔" :value="4"/>
          </el-select>
        </el-form-item>

        <!--        &lt;!&ndash; 动态附加字段 &ndash;&gt;-->
        <!--        &lt;!&ndash; 水文长观孔/混合孔的附件上传 &ndash;&gt;-->
        <!--        <el-form-item-->
        <!--          v-if="[2,4].includes(roleForm.type)"-->
        <!--          label="水位历史信息"-->
        <!--          prop="waterLevelFile"-->
        <!--        >-->
        <!--          <el-upload-->
        <!--            :action="uploadUrl"-->
        <!--            :on-success="handleUploadSuccess"-->
        <!--            :before-upload="beforeUpload"-->
        <!--            accept=".xlsx,.xls"-->
        <!--            :show-file-list="false"-->
        <!--          >-->
        <!--            <el-button size="mini" type="primary">点击上传Excel</el-button>-->
        <!--            <div slot="tip" class="el-upload__tip">请上传水位历史数据Excel文件</div>-->
        <!--          </el-upload>-->
        <!--        </el-form-item>-->

        <!-- 抽水钻孔/混合孔的附加字段 -->
        <template v-if="[3,4].includes(roleForm.type)">
          <el-form-item label="钻孔单位涌水量" prop="yieldPerUnit">
            <el-input
              v-model.number="roleForm.yieldPerUnit"
              type="number"
              style="width:300px"
              size="mini"
            >
              <template slot="append">L/(s·m)</template>
            </el-input>
          </el-form-item>

          <el-form-item label="渗透系数" prop="permeabilityCoefficient">
            <el-input
              v-model.number="roleForm.permeabilityCoefficient"
              type="number"
              style="width:300px"
              size="mini"
            >
              <template slot="append">m/d</template>
            </el-input>
          </el-form-item>

          <el-form-item label="抽/注水层位" prop="pumpNumber">
            <el-input v-model="roleForm.pumpNumber" placeholder="第x层(请填写文本内容)" style="width:300px" size="mini"/>
          </el-form-item>

          <el-form-item label="抽/注水段埋深" prop="depthRange">
            <div style="display: flex; align-items: center">
              <el-input
                v-model.number="roleForm.pumpDepthDown"
                type="number"
                placeholder="起始深度"
                style="width:120px"
              />
              <span style="margin: 0 5px">~</span>
              <el-input
                v-model.number="roleForm.pumpDepthUp"
                type="number"
                placeholder="结束深度"
                style="width:120px"
              />
              <span style="margin-left:5px">m</span>
            </div>
          </el-form-item>

          <el-form-item label="含水层观测水位" prop="waterLevel">
            <el-input
              v-model.number="roleForm.waterLevel"
              type="number"
              style="width:300px"
              size="mini"
            >
              <template slot="append">m</template>
            </el-input>
          </el-form-item>
        </template>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置编辑孔位弹层 -->
    <el-dialog
      width="600px"
      title="编辑孔位"
      :visible.sync="showExitDialog"
      @close="btnExitCancel"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="孔号" prop="holeLocationId">
              <el-input v-model="editForm.holeLocationId" size="mini" disabled/>
            </el-form-item>
            <el-form-item label="X坐标" prop="pageX">
              <el-input v-model.number="editForm.pageX" type="number" size="mini"/>
            </el-form-item>
            <el-form-item label="Y坐标" prop="pageY">
              <el-input v-model.number="editForm.pageY" type="number" size="mini"/>
            </el-form-item>
            <el-form-item label="Z坐标" prop="pageZ">
              <el-input v-model.number="editForm.pageZ" type="number" size="mini"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="孔位类型">
              <el-select
                v-model="editForm.type"
                size="mini"
                disabled
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <template v-if="[3,4].includes(editForm.type)">
              <el-form-item label="抽/注水层位" prop="pumpNumber">
                <el-input
                  v-model.number="editForm.pumpNumber"
                  type="text"
                  size="mini"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="渗透系数" prop="permeabilityCoefficient">
                <el-input
                  v-model.number="editForm.permeabilityCoefficient"
                  type="number"
                  size="mini"
                >
                  <template slot="append">m/d</template>
                </el-input>
              </el-form-item>
              <el-form-item label="单位涌水量" prop="yieldPerUnit">
                <el-input
                  v-model.number="editForm.yieldPerUnit"
                  type="number"
                  size="mini"
                >
                  <template slot="append">L/(s·m)</template>
                </el-input>
              </el-form-item>
              <el-form-item label="抽/注水段埋深 -起始深度" prop="pumpDepthDown">
                <el-input
                  v-model.number="editForm.pumpDepthDown"
                  type="number"
                  size="mini"
                >
                  <template slot="append">m</template>
                </el-input>
              </el-form-item>
              <el-form-item label="抽/注水段埋深 -结束深度" prop="pumpDepthUp">
                <el-input
                  v-model.number="editForm.pumpDepthUp"
                  type="number"
                  size="mini"
                >
                  <template slot="append">m</template>
                </el-input>
              </el-form-item>
            </template>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" size="mini" @click="submitEdit">保存</el-button>
          <el-button size="mini" @click="btnExitCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置查看详情弹层 -->
    <el-dialog
      :visible.sync="showPermissionDialog"
      title="孔位详情"
      width="700px"
    >
      <el-form :model="permissionData" label-width="140px" class="detail-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="孔号:">
              <span class="detail-value">{{ permissionData.holeLocationId }}</span>
            </el-form-item>
            <el-form-item label="X坐标:">
              <span class="detail-value">{{ permissionData.pageX }}</span>
            </el-form-item>
            <el-form-item label="Y坐标:">
              <span class="detail-value">{{ permissionData.pageY }}</span>
            </el-form-item>
            <el-form-item label="Z坐标:">
              <span class="detail-value">{{ permissionData.pageZ }}</span>
            </el-form-item>
            <el-form-item label="孔位类型:">
              <span class="detail-value">{{ getTypeName(permissionData.type) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <template v-if="[3,4].includes(permissionData.type)">
              <el-form-item label="渗透系数:">
                <span class="detail-value">{{ permissionData.permeabilityCoefficient }} m/d</span>
              </el-form-item>
              <el-form-item label="单位涌水量:">
                <span class="detail-value">{{ permissionData.yieldPerUnit }} L/(s·m)</span>
              </el-form-item>
              <el-form-item label="含水层观测水位:">
                <span class="detail-value">{{ permissionData.waterLevel }} m</span>
              </el-form-item>
              <el-form-item label="埋深范围:">
                <span class="detail-value">{{ permissionData.pumpDepthDown }} ~ {{ permissionData.pumpDepthUp }} m</span>
              </el-form-item>
            </template>
            <el-form-item label="抽/注水层位:">
              <span class="detail-value">{{ permissionData.pumpNumber }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider></el-divider>

        <el-form-item label="水位历史:" class="history-table">
          <el-table
            :data="permissionData.history"
            height="200"
            style="width: 100%"
          >
            <el-table-column prop="time" label="时间" width="180" align="center"/>
            <el-table-column prop="waterLevel" label="水位(m)" align="center"/>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="showPermissionDialog = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios'
import { updateRole, delRole } from '@/api/role'
export default {
  name: 'Role',
  data() {
    // 自定义校验规则
    const validateDepth = (rule, value, callback) => {
      if ([3, 4].includes(this.roleForm.type)) {
        if (this.roleForm.pumpDepthDown >= this.roleForm.pumpDepthUp) {
          callback(new Error('起始深度必须小于结束深度'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      editForm: {
        holeLocationId: '',
        pageX: '',
        pageY: '',
        pageZ: '',
        type: '',
        pumpNumber: '',
        waterLevel: '',
        permeabilityCoefficient: '',
        yieldPerUnit: '',
        pumpDepthDown: '',
        pumpDepthUp: ''
      },
      typeOptions: [
        { label: '地质钻孔', value: 1 },
        { label: '水文长观孔', value: 2 },
        { label: '抽水钻孔', value: 3 },
        { label: '混合孔', value: 4 }
      ],
      waterLevelFileId: null,
      uploadUrl: 'http://127.0.0.1:8080/water-level-histories/uploadWaterExcel',
      list: [],
      queryParams: {
        holeLocationId: '', // 确保字段名完全匹配
        pumpNumber: ''// 必须与v-model中的名称一致
      },
      showDialog: false, // 控制弹层显示隐藏
      showExitDialog: false,
      // 将分页信息放置到一个对象中
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      roleForm: {
        id: '',
        holeLocationId: '',
        y: '',
        x: '',
        z: '',
        type: '',
        waterLevel: '',
        time: '',
        loc: '',
        pumpNumber: '',
        yieldPerUnit: '',
        permeabilityCoefficient: '',
        pumpDepthUp: '',
        pumpDepthDown: ''
      },
      rules: {
        holeLocationId: [{ required: true, message: '请输入孔号', trigger: 'blur' }],
        x: [{ required: true, message: '请输入X坐标', trigger: 'blur' }],
        y: [{ required: true, message: '请输入Y坐标', trigger: 'blur' }],
        z: [{ required: true, message: '请输入Z高度', trigger: 'blur' }],
        type: [{ required: true, message: '请选择孔位类型', trigger: 'change' }],
        yieldPerUnit: [
          {
            required: () => [3, 4].includes(this.roleForm.type),
            message: '请输入单位涌水量',
            trigger: 'blur'
          }
        ],
        depthRange: [
          { validator: validateDepth, trigger: 'blur' }
        ],
        waterLevelFile: [
          {
            required: () => [2, 4].includes(this.roleForm.type),
            message: '请上传水位历史文件',
            trigger: 'change'
          }
        ],
        depthFrom: [
          {
            required: () => [3, 4].includes(this.roleForm.type),
            message: '请输入起始深度',
            trigger: 'blur'
          }
        ],
        depthTo: [
          {
            required: () => [3, 4].includes(this.roleForm.type),
            message: '请输入结束深度',
            trigger: 'blur'
          }
        ]
      },
      showPermissionDialog: false,
      permissionData: {
        history: [] // 初始化历史数据数组
      },
      currentRoleId: null,
      permIds: [],
      markers: []
    }
  },
  computed: {
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 修改后的编辑方法
    btnEditRow(row) {
      this.showExitDialog = true
      this.editForm = {
        holeLocationId: row.holeLocationId,
        pageX: row.pageX,
        pageY: row.pageY,
        pageZ: row.pageZ,
        type: row.type,
        waterLevel: row.waterLevel,
        pumpNumber: row.pumpNumber,
        permeabilityCoefficient: row.permeabilityCoefficient,
        yieldPerUnit: row.yieldPerUnit,
        pumpDepthDown: row.pumpDepthDown,
        pumpDepthUp: row.pumpDepthUp
      }
    },
    // 新增编辑提交方法
    async submitEdit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          try {
            await axios.post(
              `http://127.0.0.1:8080/hole-locations/update`,
              this.editForm
            )
            this.$message.success('修改成功')
            this.getRoleList()
            this.showExitDialog = false
          } catch (e) {
            this.$message.error(e.response?.data?.message || '修改失败')
          }
        }
      })
    },
    // 类型名称映射
    getTypeName(type) {
      const typeMap = {
        1: '地质钻孔',
        2: '水文长观孔',
        3: '抽水钻孔',
        4: '混合孔'
      }
      return typeMap[type] || '未知类型'
    },
    handleTypeChange(val) {
      // 切换类型时重置相关字段
      if (![3, 4].includes(val)) {
        this.roleForm.yieldPerUnit = null
        this.roleForm.permeabilityCoefficient = null
        this.roleForm.pumpLayer = ''
        this.roleForm.depthFrom = null
        this.roleForm.depthTo = null
        this.roleForm.observedWaterLevel = null
      }
      if (![2, 4].includes(val)) {
        this.roleForm.waterLevelFile = null
      }
    },

    beforeUpload(file) {
      const isExcel = file.type.includes('excel') ||
        file.name.endsWith('.xlsx') ||
        file.name.endsWith('.xls')
      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
      }
      return isExcel
    },

    handleUploadSuccess(res) {
      if (res.code === 0) {
        this.waterLevelFileId = res.data.fileId // 假设返回文件ID
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.message || '上传失败')
      }
    },
    async handleSearch() {
      try {
        let response
        if (this.queryParams.holeLocationId) {
          response = await axios.get('http://127.0.0.1:8080/hole-locations/getByHoleId', {
            params: { holeLocationId: this.queryParams.holeLocationId }
          })
        } else if (this.queryParams.pumpNumber) {
          response = await axios.get('http://127.0.0.1:8080/hole-locations/getByPumpNumber', {
            params: { pumpNumber: this.queryParams.pumpNumber }
          })
        } else {
          this.getRoleList()
          return
        }

        if (response.data.code === '0') {
          this.markers = response.data.data
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('查询失败')
      }
    },
    async getRoleList() {
      try {
        const response = await axios.get('http://localhost:8080/hole-locations/getAll')
        console.log('response.data = ', response.data)
        if (response.data.code === '0') {
          this.markers = response.data.data
        } else {
          // 查询失败
          this.$message.success('查询孔位失败')
        }
      } catch (error) {
        this.$message.success('查询孔位失败')
      }
    },
    async btnOK() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          try {
            const params = {
              holeLocationId: this.roleForm.holeLocationId,
              pageX: this.roleForm.x,
              pageY: this.roleForm.y,
              pageZ: this.roleForm.z,
              type: this.roleForm.type,
              // 文件ID参数
              waterLevelFileId: this.waterLevelFileId,
              // 抽水钻孔参数
              ...([3, 4].includes(this.roleForm.type) && {
                yieldPerUnit: this.roleForm.yieldPerUnit,
                permeabilityCoefficient: this.roleForm.permeabilityCoefficient,
                pumpNumber: this.roleForm.pumpNumber,
                pumpDepthDown: this.roleForm.pumpDepthDown,
                pumpDepthUp: this.roleForm.pumpDepthUp,
                waterLevel: this.roleForm.waterLevel
              })
            }

            await axios.post('http://127.0.0.1:8080/hole-locations/add',
              params,
              {
                headers: {
                  'Content-Type': 'application/json' // 明确指定JSON格式
                }
              }
            )
            this.$message.success('创建成功')
            this.getRoleList()
            this.btnCancel()
          } catch (e) {
            this.$message.error(e.response?.data?.message || '创建成功')
          }
        }
      })
    },

    btnCancel() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    btnExitOK() {
      this.$message.success('编辑孔位成功')
      this.btnExitCancel()
    },
    btnExitCancel() {
      this.showExitDialog = false // 关闭弹层
    },
    // 点击确定时触发
    async  btnEditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        // 下一步操作
        await updateRole({ ...row.editRow, id: row.id })
        // 更新成功
        this.$message.success('更新角色成功')
        // 更新显示数据  退出编辑状态
        // row.name = row.editRow.name // eslint的一校验 误判
        // Object.assign(target, source)
        Object.assign(row, {
          ...row.editRow,
          isEdit: true // 退出编辑模式
        }) // 规避eslint的误判
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 点击了确定触发的
    async  confirmDel(id) {
      await delRole(id) // 后端删除
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    async  btnPermission(holeLocationId, pageX, pageY, pageZ, type, waterLevel, pumpNumber, permeabilityCoefficient, yieldPerUnit, pumpDepthDown, pumpDepthUp) {
      this.showPermissionDialog = true
      this.permissionData.holeLocationId = holeLocationId
      this.permissionData.pageX = pageX
      this.permissionData.pageY = pageY
      this.permissionData.pageZ = pageZ
      this.permissionData.type = type
      this.permissionData.waterLevel = waterLevel
      this.permissionData.pumpNumber = pumpNumber
      this.permissionData.permeabilityCoefficient = permeabilityCoefficient
      this.permissionData.yieldPerUnit = yieldPerUnit
      this.permissionData.pumpDepthDown = pumpDepthDown
      this.permissionData.pumpDepthUp = pumpDepthUp
      try {
        const response = await axios.get('http://localhost:8080/water-level-histories/gets', { params: { holeid: holeLocationId }})
        console.log('根据孔位id查询水位信息', response.data)
        if (response.data) {
          this.permissionData.history = response.data.data
        } else {
          this.$message.success('未查询到数据')
        }
      } catch (error) {
        this.$message.success('捕获到异常')
      }
    }
  }
}
</script>
<style scoped>
.filter-container {
  padding: 10px;
  display: flex;
  align-items: center;
}
.detail-form ::v-deep .el-form-item {
  margin-bottom: 12px;
}

.detail-value {
  display: inline-block;
  min-width: 160px;
  padding: 0 10px;
  color: #606266;
}

.history-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: center;
  padding: 20px 0 0;
}

.el-divider {
  margin: 20px 0;
}
</style>
